package com.gin.kotlin.gf2gamecommunity.base.util

import android.app.DownloadManager
import android.content.ClipData
import android.content.ClipboardManager
import android.content.ContentResolver
import android.content.Context
import android.database.Cursor
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.widget.Toast
import androidx.core.database.getStringOrNull
import okhttp3.HttpUrl.Companion.toHttpUrl
import java.io.File

/**
 * 连接管理器
 */
val Context.connectivityManager: ConnectivityManager
    get() = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

/**
 * 判断当前是否在Wifi网络下
 * @receiver Context
 * @return Boolean
 */
fun Context.isWifiConnected() = connectivityManager.activeNetwork?.let { connectivityManager.getNetworkCapabilities(it) }?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) == true

/**
 * 下载管理器
 */
val Context.downloadManager: DownloadManager
    get() = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager

/**
 * 提交一个下载任务
 * @receiver DownloadManager
 * @param url 下载地址
 * @param relativePath （在下载文件夹中）文件保存的相对路径，含文件名，留空则直接取url最后一段
 * @return Long
 */
fun DownloadManager.enqueue(url: String, relativePath: String = url.toHttpUrl().pathSegments.last()) = this.enqueue(DownloadManager.Request(Uri.parse(url)).also {
    it.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, relativePath)
    it.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
})

/**
 * 提交一个下载任务
 * @receiver DownloadManager
 * @param url 下载地址
 * @param dir 下载目录
 * @param filename 文件名，留空则取url最后一段
 * @return Long
 */
fun DownloadManager.enqueue(url: String, dir: String, filename: String = url.toHttpUrl().pathSegments.last()) = enqueue(url, File(dir, filename).path)


/**
 * 剪贴板管理器
 */
val Context.clipboardManager: ClipboardManager
    get() = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager

/**
 * 复制文本到剪贴板
 * @receiver Context
 * @param text 文本
 * @param toast 非空时发送toast信息
 * @param label label
 * @return ClipboardManager
 */
fun Context.copyText(text: CharSequence, toast: String? = null, label: String = ""): ClipboardManager {
    toast?.also { Toast.makeText(this, it, Toast.LENGTH_SHORT).show() }
    return clipboardManager.apply { setPrimaryClip(ClipData.newPlainText(label, text)) }
}

/**
 * 获取剪贴板内容
 * @receiver Context
 * @return CharSequence?
 */
fun Context.getClipText(index: Int = 0) = clipboardManager.takeIf { it.hasPrimaryClip() }?.primaryClip?.getItemAt(index)?.text?.toString()

/**
 * 清空剪贴板
 * @receiver Context
 */
fun Context.clearClip() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        clipboardManager.clearPrimaryClip()
    } else {
        copyText("")
    }
}

/**
 * 发送Toast消息
 * @receiver Context
 * @param message String
 */
fun Context.toast(message: String) = Toast.makeText(this, message, Toast.LENGTH_SHORT).show()

/**
 * 发送“功能开发中”消息
 * @receiver Context
 * @param text String
 */
fun Context.toastDev(text: String = "...") = toast("本功能正在开发中: $text")

/**
 * 发送长消息
 * @receiver Context
 * @param message String
 */
fun Context.toastLong(message: String) = Toast.makeText(this, message, Toast.LENGTH_LONG).show()


fun Cursor.readStringOrNull(column: String) = this.getStringOrNull(this.getColumnIndex(column))

fun ContentResolver.query(uri: Uri) = query(uri, null, null, null, null)

/**
 * 从一个URI复制到指定文件
 * @receiver ContentResolver
 * @param uri Uri
 * @param destFile File
 * @return Long?
 */
fun ContentResolver.copyFile(uri: Uri, destFile: File) = openInputStream(uri)?.use { ins ->
    destFile.outputStream().use { os ->
        ins.buffered().copyTo(os)
    }
}

/**
 * 根据uri查询文件信息
 * @receiver ContentResolver
 * @param uri Uri
 * @return ContentFileInfo?
 */
fun ContentResolver.contentFileInfo(uri: Uri) = query(uri)?.use { it.moveToFirst(); ContentFileInfo(it) }


